const BasicAuth = require('basic-auth') // 提取token
const Jwt = require('jsonwebtoken') // 解析 token
const {
    jwt_config
} = global.config
const secretKey = jwt_config.serect
const expiresIn = jwt_config.expiresIn


// 解析
async function getToken(ctx, next) {
    let url = ctx.request.url
    // console.log(url)

    // 白名单
    const whiteList = [
        '/api/v1/admin/login',
        '/api/v1/test/put_token'
    ]

    const auth = whiteList.find(item => {
        return url == item
    })

    if (auth) {
        await next()
    }else {
        const token = BasicAuth(ctx.req)
        let errMsg = "无效的token"

        // 没有token
        if (!token || !token.name) {
            errMsg = "需要携带token"
            global.Response.authFail(ctx)
        }

        // 解析token
        try {
            var decode = Jwt.verify(token.name, secretKey)
            ctx.auth = {
                uid: decode.uid,
                scope: decode.scope
            }

            await next()

        } catch (error) {
            // token 不合法 过期
            if (error.name === 'TokenExpiredError') {
                errMsg = "token已过期"
            }
            global.Response.authFail(ctx,errMsg)
        }

        // if (decode.scope < this.level) {
        //     errMsg = "权限不足"
        //     throw  global.errs.Forbidden(errMsg);
        // }
    }


}


module.exports = getToken